package JAVA300.第九章容器;

/**
 * 自写linkedList
 * 添加查询方法
 */

public class TestLinkedList2 {

    private Node first;
    private Node last;
    private int size;

    public void add(Object element){
        Node node = new Node(element);

        if (first==null){
            first = node;
            last = node;

        }else {
            node.previous = last;
            node.next = null;

            last.next = node;
            //node = last;
            last = node;

        }
        size++;

    }


    public Object get(int index){//从头遍历 效率过慢，提出get1 折半查询

        if(index < 0 || index > size-1){
            throw new RuntimeException(size+"索引数组不合法");
        }

        //[a,b,c,d] 2-c
        Node temp = first;
        for (int i=0;i<index;i++){
            temp = temp.next;
        }

        return temp.element;
    }


    public Object get1(int index){//从头遍历 效率过慢，提出get1 折半查询

        if(index < 0 || index > size-1){
            throw new RuntimeException(size+"索引数组不合法");
        }

        Node temp = null;

        if(index <= (size>>1)){//在前半段

            //[a,b,c,d] 2-c


            temp = first;
            for (int i=0;i<index;i++){
                temp = temp.next;
            }

        }else {//从后往前
            System.out.println("back");
            temp = last;
            for (int i = size-1;i>index;i--) {
                temp = temp.previous;
            }

        }

        return temp.element;
    }

    @Override
    public String toString() {
        //【a,b,c】 first=a,last=c


        StringBuilder sb = new StringBuilder("[");
        Node temp = first;
      //  System.out.print("[");

        while (temp!=null){
            //System.out.print(temp.element+",");
            sb.append(temp.element+",");
            temp = temp.next;

        }
        //System.out.print("]");
        sb.setCharAt(sb.length()-1,']');
        return sb.toString();


    }



    public static void main(String[] args) {
        TestLinkedList2 linkedList = new TestLinkedList2();
        linkedList.add("a");
        linkedList.add("b");
        linkedList.add("c");
        linkedList.add("d");
        linkedList.add("e");
        linkedList.add("f");

        System.out.println(linkedList);

        System.out.println(linkedList.get1(4));
    }


}
